import Vue from 'vue'
import Vuex from 'vuex'
import $mConfig from '@/config/index.config.js'
import $mRoutesConfig from '@/config/routes.config.js'
import $mRouter from '@/common/router.js'
import utils from '@/common/utils.js'

Vue.use(Vuex)

// uni.setStorageSync("token", "oVG1b1Bgrb");
// uni.setStorageSync("openId", "oVG1b1Bgrb-l6jNYCUr6sYpQ5F-U");

const TOKEN = uni.getStorageSync("token") || "";
const USER_INFO = uni.getStorageSync("userInfo") || {};
const TOMSGUSERID = uni.getStorageSync("toMsgUserId", '') || {}; //当前接收人ID
const TOMSGGROUPID = uni.getStorageSync("toMsgGroupId", '') || {}; //当前聊天群组id
const TOMSGDETAILID = uni.getStorageSync("toMsgDetailId", '') || {}; //当前信息id
const MSGTYPE = uni.getStorageSync("msgtype", 1); //聊天类型
const CITY = uni.getStorageSync("city") || {};
const HongBaoQueue = 'hongBaoQueue'

function initWebSocket(state) {
    // const tmp = state.socketTask
    // if(tmp){
    // 	tmp = null
    // 	console.log('sockettask',state.socketTask)
    // }
    if (state.socketTask) {
        state.socketTask = null
    }
    const socket = uni.connectSocket({
        url: $mConfig.wsUrl,
        success(data) {
            console.log('连接成功', data)
        },
        fail(err) {
            console.log('连接失败', err)
        }
    });

    socket.onOpen((res) => {
        console.log('opensss')

        state.is_open_socket = true;
        /**
         * 发送登陆
         */
        sendLogin(state)

        uni.onSocketClose(function(res) {
            console.log('=----------------WebSocket 已关闭！');
            state.is_open_socket = false;
            state.socketTask = null

        });
    })
    socket.onMessage(function(res) {
        const {
            code,
            type,
            msg
        } = JSON.parse(res.data);

        // 红包逻辑
        if (type === 'publishRedPacket') {
            utils.handleHongbao(msg)
        }

        if (type === 'chat' || type === 'offline_chat') {

            utils.handleMessage(JSON.parse(res.data))
        }

        uni.$emit('websocket-message-process', res)

        if (code == 401) {
            state.logoutFlag = true
            state.userInfo = ''
            setTimeout(() => {
                uni.redirectTo({
                    url: '/pages/login/login',
                    success() {
                        console.log('redirect success')
                    },
                    fail(err) {
                        console.log('redirect fail', err)
                    }
                })
                // #ifdef APP-PLUS
                plus.nativeUI.toast("您的账号已在其他设备登录");
                // #endif
                // uni.showToast({
                // 	title: "您的账号已在其他设备登录！",
                // 	icon:none,
                // 	duration: 3000
                // });
            }, 3000)
        }
    })
    return socket
}

function sendLogin(state) {
   
    state.socketTask.send({
        data: JSON.stringify({
            type: 'login',
            msg: {
                userId: state.userInfo.id,
                name: state.userInfo.name,
                clientId: state.userInfo.clientId
            }
        }),
       
    });
    // //获取离线消息
    // state.socketTask.send({
    // 	data: JSON.stringify({
    // 		type: 'offline_chat'
    // 	}),
    // 	async success(res) {
    // 		console.log("消息发送成功offline_chat");
    // 	}
    // });
}

function reConnection(state) {
    clearTime(state.interval)
    state.interval = setInterval(() => {
        uni.onNetworkStatusChange(function(res) {
         
            if (!res.isConnected) {
                console.log('网络断开')
                state.is_open_socket = false
            }
        })
  
        if (!state.is_open_socket && !state.logoutFlag) {
            state.socketTask = initWebSocket(state)
        }
    }, 1000)
    sendHeartTimeOut(state)
}

function sendHeartTimeOut(state) {
    state.pingInterval = setInterval(() => sendHeart(state), 7000)
    console.log('执行心跳', state.pingInterval)
}



function sendHeart(state) {
    if (state.socketTask)
        state.socketTask.send({
            data: '0X9',
    
            fail() {
              
                state.is_open_socket = false
            }
        })


}

function clearTime(state) {
    clearInterval(state.interval)
   
    clearInterval(state.pingInterval)
}

function logout(state) {
   
    //state.socketTask.close()
    state.logoutFlag = true
    state.is_open_socket = false
    clearInterval(state.interval)
}

const store = new Vuex.Store({
    state: {
        // 是否強制登录
        forcedLogin: $mConfig.forcedLogin,
        // 前端token
        token: TOKEN,
        // 用户信息 头像 昵称
        userInfo: USER_INFO,
        // 聊天对象
        toMsgUserId: TOMSGUSERID,
        // 聊天群
        toMsgGroupId: TOMSGGROUPID,
        // 聊天群
        toMsgDetailId: TOMSGDETAILID,
        // 当前群聊类型
        msgtype: MSGTYPE,
        // 选择城市
        city: CITY,
        socketTask: null,
        //是否主动退出 true是主动 
        logoutFlag: false,
        interval: 0,
        pingInterval: 0

    },
    getters: {
        // 用户是否登录
        hasLogin: state => {
            if (state.token) {
                return true;
            } else {
                return false
            }
        }
    },
    mutations: {
        SET_TOKEN(state, token) {
         
            state.token = token;
            uni.setStorageSync("token", token);
        },
        SET_CITY(state, city) {
            state.city = city;
            uni.setStorageSync("city", city);
        },
        SET_LOGOUT(state) {
            state.token = "";
            uni.setStorageSync("token", "");
        },
        SET_TOMSGUSERID(state, toMsgUserId) {
            state.toMsgUserId = toMsgUserId;
            uni.setStorageSync("toMsgUserId", toMsgUserId);
        },
        SET_TOMSGGROUPID(state, toMsgGroupId) {
            state.toMsgGroupId = toMsgGroupId;
            uni.setStorageSync("toMsgGroupId", toMsgGroupId);
        },
        SET_TOMSGDETAILID(state, toMsgDetailId) {
            state.toMsgDetailId = toMsgDetailId;
            uni.setStorageSync("toMsgDetailId", toMsgDetailId);
        },
        SET_MSGTYPE(state, msgtype) {
            state.msgtype = msgtype;
            uni.setStorageSync("msgtype", msgtype);
        },
        SET_USERINFO(state, userInfo) {
            state.userInfo = userInfo;
            uni.setStorageSync("userInfo", userInfo);
            state.logoutFlag = userInfo == '' ? true : false
            if (state.logoutFlag) {
                logout(state)
            } else {
                if (!state.is_open_socket)
                    reConnection(state)
                else
                    sendLogin(state)
            }
        },
        WEBSOCKET_INIT(state, url) {
            // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
            state.socketTask = initWebSocket(state)

            // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】

            // state.socketTask.onClose(function() {
            // 	setInterval(() => {
      
            // 		if (!state.is_open_socket) {
            // 			state.socketTask = initWebSocket()

            // 		}
            // 	}, 1000)

            // })

            // state.socketTask.onMessage(function(){

            // })

            state.socketTask.onClose(() => {

                // reConnection(state)
            })
        },
        WEBSOCKET_SEND(state, p) {
         
            state.socketTask && state.socketTask.send({
                data: p,
                async success(res) {

                }
            });
        },
        WEBSOCKET_CLOSE(state) {
       
            logout(state)
            uni.onSocketClose(function(res) {
                console.log('WebSocket 已关闭！');
            });

        },
        WS_INTERVAL(state) {
            reConnection(state)
        },
        WS_LOGOUT(state) {
            state.logoutFlag = true
            console.log('logout ', state.logoutFlag)
            state.socketTask.send({
                data: JSON.stringify({
                    'type': 'logout'
                }),
                success() {

                }
            })
        }
    },
    actions: {
        // 登录过期 重新登录
        reLogin({
            commit
        }, info) {
            commit("SET_USERINFO", "");
            uni.navigateTo({
                url: "../login/login"
            })

        },
        WEBSOCKET_INIT({
            commit
        }, url) {
            commit('WEBSOCKET_INIT', url)
        },
        WEBSOCKET_SEND({
            commit
        }, p) {
            commit('WEBSOCKET_SEND', p)
        },
        WS_INTERVAL({
            commit
        }) {
            commit('WS_INTERVAL')
        },
        WS_LOGOUT({
            commit
        }) {
            commit("WS_LOGOUT")
        }
    }
})

export default store
